﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Work.ProtoclBase;

namespace System.Work.ClientEngine.FPXH
{
    #region Read
    public class FPXHReadCommand : IFPXHCommand<ReadDataEventArgs, FPXHCommandPrefix>
    {
        public string Name
        {
            get
            {
                return "r";
            }
        }

        public void ExecuteCommand(EventHandler<ReadDataEventArgs> handle, BufferedPackageInfo package, FPXHCommandPrefix prefix)
        {
            if (handle == null) return;
            var buff = package.Data[0].Array;
            //解析命令
            string cmd = Encoding.ASCII.GetString(buff);
            ReadDataEventArgs args = prefix.CurFormat.AnalysisReadPacket(cmd, prefix.Count) as ReadDataEventArgs;
            args.Address = prefix.Address;
            handle(null, args);
        }
    }
    #endregion
    #region Write
    public class FPXHWriteCommand : IFPXHCommand<WriteDataEventArgs, FPXHCommandPrefix>
    {
        public string Name
        {
            get
            {
                return "w";
            }
        }

        public void ExecuteCommand(EventHandler<WriteDataEventArgs> handle, BufferedPackageInfo package, FPXHCommandPrefix prefix)
        {
            if (handle == null) return;
            var buff = package.Data[0].Array;
            //解析命令
            string cmd = Encoding.ASCII.GetString(buff);
            WriteDataEventArgs args = prefix.CurFormat.AnalysisWritePacket(cmd) as WriteDataEventArgs;
            args.Address = prefix.Address;
            handle(null, args);
        }
    }
    #endregion
    #region Error
    public class FPXHErrorCommand : IFPXHCommand<ErrorDataEventArgs, FPXHCommandPrefix>
    {
        public string Name
        {
            get
            {
                return "e";
            }
        }

        public void ExecuteCommand(EventHandler<ErrorDataEventArgs> handle, BufferedPackageInfo package, FPXHCommandPrefix prefix)
        {
            if (handle == null) return;
            var args = new ErrorDataEventArgs();
            try
            {
                //TODO:
                //var buff = package.Data[0].Array;
                //var respCode = String.Concat(buff[10].ToString("X2"), buff[9].ToString("X2"));
                //args.ErrorCode = respCode;
                //var error = buff;
                //var s = new StringBuilder();
                //for (int i = 0; i < error.Length; i++)
                //{
                //    s.AppendFormat("{0} ", error[i].ToString("X2"));
                //}
                //args.ErrorMsg = s.ToString();
            }
            catch (Exception ex)
            {
                args.ErrorCode = "program_error";
                args.ErrorMsg = ex.Message;
            }
            handle(null, args);
        }
    }
    #endregion
}
